# == Schema Information
# Schema version: 20080914230643
#
# Table name: users
#
#  id            :integer(4)      not null, primary key
#  username      :string(255)     default(""), not null
#  password_salt :string(255)     default(""), not null
#  password_hash :string(255)     default(""), not null
#  person_id     :integer(4)
#  created_at    :datetime
#  updated_at    :datetime
#

require 'digest/sha2'

class User < ActiveRecord::Base
	belongs_to :person
	has_and_belongs_to_many :roles

	validates_presence_of :username, :password
	validates_length_of		:password, :minimum => 5
	validates_uniqueness_of :username
	
	attr_reader :password
	
	def password=(clear_text_password)
		@password = clear_text_password
		self.password_salt = calculate_salt(rand)
		self.password_hash = self.class.calculate_password_hash(clear_text_password, password_salt)
	end

	def calculate_salt(number)
			raw_salt = self.object_id.to_s + number.to_s
			Digest::SHA256.hexdigest(raw_salt)[0..39]
	end
	
	def self.calculate_password_hash(clear_text_password, salt)
		Digest::SHA256.hexdigest(clear_text_password + salt)
	end
	
	def self.authenticate(username, password)
		user = find_by_username(username)
		if (user)
			if (user.password_hash != User.calculate_password_hash(password, user.password_salt))
				user = nil
			end
		end
		user	
	end
	
	def has_role(role_name)
		role(role_name) != nil
	end
	
	def role(role_name)
		roles.detect do |role|
			role.name == role_name
		end
	end
	
	def self.reset_password(user)
		new_password = random_password(user)
		user.password = new_password
		user.save!
		Mailer.deliver_reset_password(user.person, new_password)
	end
	
	def self.random_password(user)
		user.calculate_salt(rand)[0..7]
	end
end
